package cn.com.dhc.zzz.back.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.bbs.ba.Timer.MiaoAction;
import cn.bbs.ba.base.BAAction;
import cn.bbs.ba.base.BaseDto;
import cn.bbs.ba.html.ZPaiInit;
import cn.com.zzz.pk.dto.PkPepole;
import cn.com.zzz.pk.dto.PkTable;

/**
 * 退出游戏
 */
public class PKExitGameAction extends BAAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String userNo = request.getParameter("userName");
		Iterator iterator2= ZPaiInit.getTable().entrySet().iterator(); 
    	List<BaseDto> retList = new ArrayList<BaseDto>();
    	PkTable table = null;
    	while(iterator2.hasNext()){  
    		Map.Entry  entry= (Map.Entry)iterator2.next(); 
    		table = (PkTable)entry.getValue();
			// 取出用户
			List<PkPepole> peopleList = (List<PkPepole>)table.getValue("people");
			
    		// 正在打牌中
    		if("1".equals(table.getStt())
    				|| "2".equals(table.getStt())) {
    			// 判断用户是不是在出牌。
    			for(int i = 0; i < peopleList.size(); i++) {
    				PkPepole people = peopleList.get(i);
    				// 押注中并且等待押注时间是0的时候
    				if(people.getUserNo().equals(userNo)) {
						if (StringUtils.isEmpty(table.getString("outUserNo"))) {
							table.setValue("outUserNo", people.getUserNo());
						}
						else {
							table.setValue("outUserNo", table.getString("outUserNo") + "," + people.getUserNo());
						}
						
						// 如果当前是押注中 需要算出下个出牌者
						if (people.getStt().equals("2")) {
							// 当前选手做弃牌处理
							people.setStt("3");
							people.setDdTime("");
							MiaoAction.nextOut(table, people.getAtWhere());
						}
						else {
							// 当前选手做弃牌处理
							people.setStt("3");
							people.setDdTime("");
						}

						break;
    				}
    			}
    		}
    		// **************等待打牌 并且两个人以上（包含两个人）*****************
    		else if("0".equals(table.getStt())) {
    			// 判断用户是不是在出牌。
    			for(int i = 0; i < peopleList.size(); i++) {
    				PkPepole people = peopleList.get(i);
    				// 退出房间
    				if(people.getUserNo().equals(userNo)) {
    					peopleList.remove(i);
    					ZPaiInit.getUserMap().remove(people.getUserNo());
    					break;
    				}
    			}
    		}
    	}
		// 用户已经存在
		return mapping.findForward("success");
	}

}
